package com.example.demo.service;

import com.example.demo.core.AppServer;
import com.example.demo.core.ICommander;
import com.example.demo.pojo.Slave;
import com.example.demo.util.Command;
import com.example.demo.util.DefaultException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SlaveService {

    Map<String, Slave> slaves = new ConcurrentHashMap<>();

    @Autowired
    AppServer commander;

    public void update(Slave slave) {
        this.slaves.put(slave.getUuid(), slave);
    }

    public void add(Slave slave) {
        this.slaves.put(slave.getUuid(), slave);
    }

    public void remove(String uuid) {
        this.slaves.remove(uuid);
    }

    public List<Slave> getAllSlave() {
        return new ArrayList<>(this.slaves.values());
    }

    public boolean setMasterVolume(Slave slave) throws DefaultException {
        int level = slave.getMaster_volume();
        if ( level >= 0 && level <= 100 ) {
            try {
                commander.sendCommand(slave.getUuid(), Command.SET_MASTER_VOLUME, new String[]{String.valueOf(level)});
                return true;
            } catch (IOException e) {
                throw new DefaultException(e);
            }
        }
        return false;
    }
}
